package com.lagou.web;

import com.lagou.domain.LoginResponse;
import com.lagou.domain.User;
import com.lagou.service.LoginService;
import com.lagou.util.GetPostJson;
import com.lagou.util.JsonUtil;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;


public class LoginController extends HttpServlet {

	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取post请求的请求体
		String postJson = GetPostJson.getPostJson(req);
		// 将请求体转为对象
		User user  = JsonUtil.json2Object(postJson,User.class);
		// 记录是否存在此账号密码的布尔值
		boolean isExits;
        try {
        	//将布尔值赋值，如果数据库返回的记录 > 0则说明存在，值为true 否则为false
            isExits = LoginService.loginService(user.getUsername(), user.getPassword());
            if(isExits) {
            	// 表示登陆成功，将已登录的状态记录到session中
				HttpSession session = req.getSession();
				session.setAttribute("isLogin",true);
				//返回给客户端登陆成功的信息
				resp.getWriter().write(JsonUtil.object2Json(new LoginResponse(200,"登陆成功")));
            } else {
            	//返回给客户端登陆失败的信息
                resp.getWriter().write(JsonUtil.object2Json(new LoginResponse(-1,"登陆失败")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
